<?php
namespace app\school\middleware;
use app\user\logic\account\UserToken;
use app\common\exception\UnauthorizedException;

class CheckLogin
{
    public function handle($request, \Closure $next)
    {

        // 如果引用了路由登录排除中间件,则不进行登录检查
        if ($request->needLogin === false) {
            return $next($request);
        }

        // 进行登录验证
        $ak = $request->header('E-USER-AK','');
        $sk = $request->header('E-USER-SK','');
        if(!$ak || !$sk){
            throw new UnauthorizedException();
        }

        // 获取用户
        $user = app(UserToken::class)->getUserWithToken($ak,$sk);
        if($user === false){
            throw new UnauthorizedException();
            
        }

        $request->user = $user;

        return $next($request);
    }

}
